import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { removeType3Items } from '@/utils/menu';
import {MenuItem} from "@/types/global";

interface MenuState {
  menuList: MenuItem[];
  setMenuList: (list: MenuItem[]) => void;
  pageList: MenuItem[];
  updatePageList: () => void;
  authItems: Record<string, string[]>;
  flatMenuList: MenuItem[];
  keepAlive: Record<string, React.ReactNode>;
  addKeepAlive: (key: string, component: React.ReactNode) => void;
  removeKeepAlive: (key: string) => void;
}
const useMenuStore = create<MenuState>()(
  devtools(
    persist(
      immer<MenuState>((setState, getState) => ({
        menuList: [],
        flatMenuList: [],
        setMenuList: (list: MenuItem[] = []) => {
          // 使用setState方法更新userInfo
          setState((state) => {
            state.menuList = list;

            const flatten = (menus: MenuItem[]): MenuItem[] => {
              return menus.reduce<MenuItem[]>((acc, cur) => {
                acc.push(cur);
                if (cur.children) {
                  acc.push(...flatten(cur.children));
                }
                return acc;
              }, []);
            };
            state.flatMenuList = flatten(list);
          });
        },
        pageList: [],
        authItems: {},
        updatePageList: () => {
          const menulist = getState().menuList;
          const { acc, authItems } = removeType3Items(menulist);
          setState((state) => {
            state.pageList = acc;
            state.authItems = authItems;
          });
        },
        keepAlive: {},
        addKeepAlive: (key: string, component: React.ReactNode) => {
          setState((state) => {
            state.keepAlive[key] = component;
          });
        },
        removeKeepAlive: (key: string) => {
          setState((state) => {
            delete state.keepAlive[key];
          });
        },
      })),
      { name: 'menu' },
    ),
  ),
);
export default useMenuStore;
